//
//  StringExtension.swift
//  CarHailingDriver
//
//  Created by xiqiang.zhu on 2019/7/5.
//  Copyright © 2019 iOS-team. All rights reserved.
//

import UIKit

extension String {
    
    /// 计算字符串高度
    /// - Parameter forWidth: 预估宽度
    /// - Parameter font: 字体
    public func calcHeight(forWidth: CGFloat, font: UIFont?) -> CGFloat {
        guard let font = font else { return 0 }
        let rect = CGSize(width: forWidth, height: .greatestFiniteMagnitude)
        let boundingRect = self.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
        return ceil(boundingRect.height)
    }
    
    
    /// 计算字符串宽度
    /// - Parameter forHeight: 预估高度
    /// - Parameter font: 字体
    public func calcWidth(forHeight: CGFloat, font: UIFont?) -> CGFloat {
        guard let font = font else { return 0 }
        let rect = CGSize(width: .greatestFiniteMagnitude, height: forHeight)
        let boundingRect = self.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
        return ceil(boundingRect.width)
    }
    
    static func verify(_ string1: String, string2: String) -> String?{
        if string1.count != 0 {
            return string1
        }else if string2.count != 0 {
            return string2
        }
        return nil
    }
}

extension NSAttributedString {
    
    /// 计算富文本字体高度
    /// - Parameter forWidth: 预估宽度
    public func calcHeight(forWidth: CGFloat) -> CGFloat {
        let rect = CGSize(width: forWidth, height: .greatestFiniteMagnitude)
        let boundingRect = self.boundingRect(with: rect, options: .usesLineFragmentOrigin, context: nil)
        return ceil(boundingRect.height)
    }
    
    /// 计算富文本字体宽度
    /// - Parameter forWidth: 预估高度
    public func calcWidth(forHeight: CGFloat) -> CGFloat {
        let rect = CGSize(width: .greatestFiniteMagnitude, height: forHeight)
        let boundingRect = self.boundingRect(with: rect, options: .usesLineFragmentOrigin, context: nil)
        return ceil(boundingRect.width)
    }
}

